/*
 * em_406a.c
 *
 *  Created on: Jun 22, 2011
 *      Author: ben
 */

#include <avr/io.h>

#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>

#include "em_406a.h"
#include "usart.h"

void GPSInit(uint16_t ubrr_value)
{
//	UBRR0L = ubrr_value;
//	UBRR0H = (ubrr_value >> 8);
//	UCSR0B = (1 << RXEN0) | (1 << TXEN0);
//	UCSR0C = (1 << USBS0) | (1 << UCSZ01) | (1 << UCSZ00);
	usart_init(&PORTC, &USARTC0, 4800);
	usart_rx_buf_flush();
}

void GPSWrite(char data)
{
	usart_send_byte(data);
}

char GPSRead()
{
//	while (!(UCSR0A & (1 << RXC0))) {}
//	return UDR0;
	while (!USART_IsRXComplete(&USARTC0));
	return USART_GetChar(&USARTC0);
}

GPS_DATA processGGA(char buffer[NMEA_BUFFER_SIZE])
{
	GPS_DATA gpsData;
	gpsData.fixErr = 0;
	char *endptr;
//	double degrees, minutesfrac;
	int i = 0;
	if (buffer[i] == ',')
		i++;

	//UTC Time [hhmmss.sss]
	gpsData.fix_time = strtod(&buffer[i], &endptr);
	while(buffer[i++] != ',');

	//Latitude [ddmm.mmmmm]
	gpsData.latitude = strtod(&buffer[i], &endptr);
//	gpsData.latitude = 41.324722;
//	minutesfrac = modf(gpsData.latitude/100, &degrees);
//	gpsData.latitude = degrees + (minutesfrac*100)/60;
	gpsData.latitude = gpsData.latitude/100;
	while(buffer[i++] != ',');

	//North/South
	if (buffer[i] == 'S')
	{
		gpsData.latitude = -gpsData.latitude;
		gpsData.NS = 'S';
	}
	else
		gpsData.NS = 'N';
	while(buffer[i++] != ',');

	//Longitude [ddmm.mmmmm]
	gpsData.longitude = strtod(&buffer[i], &endptr);
//	gpsData.longitude = 105.570556;
//	minutesfrac = modf(gpsData.longitude/100, &degrees);
//	gpsData.longitude = degrees + (minutesfrac*100)/60;
	gpsData.longitude = gpsData.longitude/100;
	while(buffer[i++] != ',');

	//East/West
	if (buffer[i] == 'W')
	{
		gpsData.longitude = -gpsData.longitude;
		gpsData.EW = 'W';
	}
	else
		gpsData.EW = 'E';
	while (buffer[i++] != ',');

	if ((abs(gpsData.latitude) < 10) | (abs(gpsData.longitude) < 10))
		gpsData.fixErr = 1;

	return gpsData;
}

GPS_DATA GPSGetCoord()
{
	char nmeaSent[5];
	char readVal;
	char nmeaBuffer[NMEA_BUFFER_SIZE];

	do
		readVal = GPSRead();
	while (readVal != '$');

	for (int i = 0; i < 5; i++)
		nmeaSent[i] = GPSRead();

	if (!(strcmp(nmeaSent, "GPGGA")))
	{
		for (int i = 0; i < NMEA_BUFFER_SIZE; i++)
		{
			nmeaBuffer[i] = GPSRead();
			if (nmeaBuffer[i] == '$')
				break;
		}
	}
	return processGGA(nmeaBuffer);
}
